<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    ></el-form>
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="440px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
        style="margin-left: 55px"
      >
        <el-col :span="24">
          <el-form-item label="父项代码" prop="dylFxdm">
            <el-input
              v-model="queryParams.dylFxdm"
              placeholder="请输入父项物料代码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="子项代码" prop="dylZxdm">
            <el-input
              v-model="queryParams.dylZxdm"
              placeholder="请输入子项物料代码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="代用物料" prop="dylWldm">
            <el-input
              v-model="queryParams.dylWldm"
              placeholder="请输入代用物料代码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(false)"
          v-hasPermi="['project:dylList:add']"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(true)"
          v-hasPermi="['project:dylList:addmul']"
        >
          批量新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit(selection[0])"
          v-hasPermi="['project:gclList:add']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:dylList:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['project:dylList:export']"
        >
          导出
        </el-button>
      </el-col>
      <el-col :span="2.2" style="position: absolute; right: 35px; top: 0">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dylListList"
      border
      :height="tableH"
      stripe
      :row-style="{ padding: '0px' }"
      :cell-style="{ padding: '0px' }"
      :header-row-style="{ padding: '2px' }"
      :header-cell-style="{ 'text-align': 'center', padding: '2px' }"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="父项代码"
        align="center"
        width="130"
        prop="dylFxdm"
      />
      <el-table-column label="品名规格" width="250" prop="dylFxdmmc" />
      <el-table-column
        label="子项代码"
        align="center"
        width="130"
        prop="dylZxdm"
      />
      <el-table-column
        label="子项用量"
        align="center"
        width="130"
        prop="dylZxdmYl"
      />
      <el-table-column label="品名规格" width="250" prop="dylZxdmmc" />
      <el-table-column
        label="代用物料"
        align="center"
        width="130"
        prop="dylWldm"
      />
      <el-table-column
        label="代用用量"
        align="center"
        width="130"
        prop="dylWldmYl"
      />
      <el-table-column label="品名规格" width="300" prop="dylWldmmc" />
      <el-table-column label="默认代用" align="center" prop="dylDefult">
        <template #default="scope">
          <el-switch
            v-model="scope.row.dylDefult"
            active-value="1"
            inactive-value="0"
            @change="handleDyDefault(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="比例%"
        align="center"
        width="100"
        prop="dylRate"
      />
      <el-table-column
        label="建立人员"
        align="center"
        width="80"
        prop="createBy"
      />
      <el-table-column
        label="建立日期"
        align="center"
        prop="createTime"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更改人员" align="center" prop="updateBy" />
      <el-table-column
        label="更改日期"
        align="center"
        prop="updateTime"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['project:dylList:add']"
            >修改</el-button
          >
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['project:dylList:remove']">
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改代用料信息维护对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="750px"
      append-to-body
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10" v-if="!isBatch">
          <el-col :span="10">
            <el-form-item label="父项代码" prop="dylFxdm">
              <el-autocomplete
                class="inline-input"
                v-model="form.dylFxdm"
                :fetch-suggestions="querySearch"
                placeholder="请输入父项代码"
                :trigger-on-focus="false"
                @select="handleSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="品名规格" prop="dylFxdmmc">
              <HdSelectMaterial
                v-model="form.dylFxdmmc"
                keyName="itmPmgg"
                @change="
                  (res) => {
                    form.dylFxdm = res.itmWldm;
                    handleSelect(res);
                  }
                "
              ></HdSelectMaterial>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="10">
          <el-form-item label="子项代码" prop="dylZxdm">
            <el-select
              v-if="!isBatch"
              v-model="form.dylZxdm"
              placeholder="请先选择父项代码"
              value-key="bodZxdm"
              @change="handleSelectCh"
            >
              <el-option
                v-for="dict in restaurants"
                :key="dict.bodZxdm"
                :label="dict.bodZxdm"
                :value="dict"
              ></el-option>
            </el-select>
            <HdSelectMaterial
              v-else
              v-model="form.dylZxdm"
              @change="
                (res) => {
                  form.dylZxdmmc = res.itmPmgg;
                }
              "
            ></HdSelectMaterial>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="品名规格" prop="dylZxdmmc">
            <el-input v-model="form.dylZxdmmc" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="子项用量" prop="dylZxdmYl">
            <el-input
              disabled
              v-model="form.dylZxdmYl"
              placeholder="请输入子项用量"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="代用物料" prop="dylWldm">
            <el-autocomplete
              class="inline-input"
              v-model="form.dylWldm"
              :fetch-suggestions="querySearch"
              placeholder="请输入代用物料"
              :trigger-on-focus="false"
              @select="handleSelectWldm"
            ></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="品名规格" prop="dylWldmmc">
            <el-input v-model="form.dylWldmmc" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="代用用量" prop="dylWldmYl">
            <el-input
              v-model="form.dylWldmYl"
              placeholder="请输入代用用量"
              :disabled="isBatch"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="默认代用" prop="dylDefult">
            <el-switch
              v-model="form.dylDefult"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="代用比例" prop="dylRate">
            <el-input v-model="form.dylRate" style="width: 150px"
              ><span slot="suffix" style="margin: 0 3px">%</span></el-input
            >
          </el-form-item>
        </el-col>
      </el-form>
      <el-table
        v-if="title === '添加代用料信息维护'"
        v-loading="loading"
        :data="dylFxZxSelect"
      >
        <el-table-column label="父项代码" align="center" prop="dylFxdm" />
        <el-table-column label="品名规格" prop="dylFxdmmc" />
        <el-table-column label="子项代码" align="center" prop="dylZxdm" />
        <el-table-column label="品名规格" prop="dylZxdmmc" />
        <el-table-column label="代用物料" align="center" prop="dylWldm" />
        <el-table-column label="品名规格" prop="dylWldmmc" />
        <el-table-column label="默认代用" align="center" prop="dylDefult">
          <template #default="scope">
            <dict-tag
              :options="dylDefultOptions"
              :value="scope.row.dylDefult"
            />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--   删除或者更新默认代用弹窗 -->
    <el-dialog
      title="请先选择其他默认的代用"
      v-model="dylDefultOpen"
      :close-on-click-modal="false"
      draggable
      width="950px"
      append-to-body
      :before-close="handleDefClose"
    >
      <el-table
        v-loading="loading"
        :data="dylDefultList"
        border
        stripe
        :row-style="{ padding: '0px' }"
        :cell-style="{ padding: '0px' }"
        :header-row-style="{ padding: '2px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '2px' }"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="父项代码" align="center" prop="dylFxdm" />
        <el-table-column label="品名规格" align="center" prop="dylFxdmmc" />
        <el-table-column label="子项代码" align="center" prop="dylZxdm" />
        <el-table-column label="品名规格" align="center" prop="dylZxdmmc" />
        <el-table-column label="代用物料" align="center" prop="dylWldm" />
        <el-table-column label="品名规格" align="center" prop="dylWldmmc" />
        <el-table-column label="默认代用" align="center" prop="dylDefult">
          <template #default="scope">
            <el-switch
              v-model="scope.row.dylDefult"
              active-value="1"
              inactive-value="0"
              @change="handleDyDefault(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDylList,
  getDylList,
  delDylList,
  addDylList,
  updateDylList,
  exportDylList,
  fuzzyMatching,
  getDylByFxZx,
  getDylListById,
  judgeBomAc,
  addBatch,
} from "@/api/project/dylList";
import { selectByOrders } from "@/api/project/bom";

export default {
  name: "DylList",
  data() {
    return {
      state2: "",
      restaurants: [],
      selection: [],
      tableH: document.body.clientHeight - 290,
      dyWldm: [],
      wldm: "",
      isBatch: false,
      //父项代码
      dylFxdm: "",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      dylDefults: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代用料信息维护表格数据
      dylListList: [],
      // 默认代用料
      dylDefultOptions: [
        { dictLabel: "Yes", dictValue: "true" },
        { dictLabel: "No", dictValue: "false" },
      ],
      // 查询父项子项返回的数据
      dylFxZxSelect: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSearch: false,
      dylDefultOpen: false,
      // 有效表示字典
      dylFlagOptions: [],
      //代用料
      dylDefultList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 35,
        dylFxdm: null,
        dylZxdm: null,
        dylWldm: null,
      },
      Fxdm: null,
      Zxdm: null,
      FxdmOld: null,
      ZxdmOld: null,
      // 表单参数
      form: {
        dylId: null,
        dylFxdm: null,
        dylFxdmmc: null,
        dylZxdm: null,
        dylZxdmmc: null,
        dylWldm: null,
        dylWldmmc: null,
        dylDefult: null,
        dylFlag: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        dylRate: undefined,
        dylZxdmYl: undefined,
        dylWldmYl: undefined,
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_flag").then((response) => {
      this.dylFlagOptions = response.data;
    });
  },
  computed: {
    // 表单校验
    rules() {
      let r = {
        dylFxdm: [
          { required: true, message: "父项代码不能为空", trigger: "blur" },
        ],
        dylZxdm: [
          { required: true, message: "子项代码不能为空", trigger: "blur" },
        ],
        dylWldm: [
          { required: true, message: "代用物料不能为空", trigger: "blur" },
        ],
        dylRate: [
          { required: true, message: "代用比例不能为空", trigger: "blur" },
        ],
        dylWldmYl: [
          { required: true, message: "代用用量不能为空", trigger: "blur" },
        ],
      };
      if (this.isBatch) {
        delete r.dylFxdm;
        delete r.dylWldmYl;
      }
      return r;
    },
  },
  methods: {
    /** 查询代用料信息维护列表 */
    getList() {
      this.loading = true;
      listDylList(this.queryParams).then((response) => {
        this.dylListList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
      this.handleClose();
    },
    // 表单重置
    reset() {
      this.form = {
        dylId: null,
        dylFxdm: null,
        dylFxdmmc: null,
        dylZxdm: null,
        dylZxdmmc: null,
        dylWldm: null,
        dylWldmmc: null,
        dylDefult: null,
        dylFlag: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        dylRate: undefined,
      };
      this.resetForm("form");
    },
    //

    querySearch(queryString, cb) {
      fuzzyMatching(queryString).then((response) => {
        this.dyWldm = response.data;
        // this.loading = false;
        this.restaurants = this.dyWldm;
        for (let item of this.restaurants) {
          item.value = item.itmWldm;
        }
        cb(this.restaurants);
      });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.value;
      };
    },
    handleClose() {
      const a = ({ a: 1 }, { b: 1 });

      this.Fxdm = null;
      this.Zxdm = null;
      this.open = false;
      this.dylFxZxSelect = [];
    },
    handleDefClose() {
      this.getList();
      this.dylDefultOpen = false;
    },
    //父项
    handleSelect(item) {
      this.Fxdm = item.itmWldm;
      this.handleSelectIs();
      this.form.dylFxdmmc = item.itmPmgg;
      selectByOrders(this.Fxdm, 0, 1).then((res) => {
        if (res.data && res.data.length > 0) {
          this.dyWldm = res.data;
          this.restaurants = this.dyWldm;
        } else {
          this.msgError("该父项bom无子级,请建立bom后再进行代用料维护!");
        }
      });
    },
    //子项
    handleSelectCh(item) {
      this.form.dylZxdm = item.bodZxdm;
      this.Zxdm = item.itmWldm;
      this.form.dylZxdmYl = item.bodDwyl;
      this.form.dylZxdmmc = item.itmPmgg;
      // this.handleSelectIs()
    },
    //
    handleSelectIs() {
      if (this.Zxdm != null && this.Fxdm != null) {
        let query = {};
        query.dylFxdm = this.Fxdm;
        query.dylZxdm = this.Zxdm;
        getDylByFxZx(query).then((response) => {
          this.dylFxZxSelect = response.data;
        });
      }
    },
    handleSelectWldm(item) {
      this.form.dylWldmmc = item.itmPmgg;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
      this.ids = selection.map((item) => item.dylId);
      this.dylDefults = selection.map((item) => item.dylDefult);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(val) {
      this.isBatch = val;
      this.open = true;
      this.title = "添加代用料信息维护";
      this.reset();
    },
    handleSearch() {
      this.title = "查询机台特性";
      this.openSearch = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!this.isBatch) {
            judgeBomAc({
              bodFxdm: this.form.dylFxdm,
              bodZxdm: this.form.dylZxdm,
            }).then((res) => {
              if (this.form.dylId) {
                this.handleDyDefault(this.form);
              } else {
                addDylList(this.form).then((response) => {
                  this.msgSuccess("新增成功");
                  // this.open = false
                  this.getList();
                  this.form = {
                    ...this.form,
                    dylId: null,
                    dylFxdm: null,
                    dylFxdmmc: null,
                  };
                });
              }
            });
          } else {
            addBatch(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.form = {
                ...this.form,
                dylId: null,
                dylFxdm: null,
                dylFxdmmc: null,
              };
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dylIds = row.dylId || this.ids;
      const dylDefults = this.dylDefults || row.dylDefult;
      if (dylDefults === "1") {
        getDylListById(row.dylId || this.ids).then((response) => {
          this.dylDefultList = response.data;
          if (this.dylDefultList.length > 0) {
            this.dylDefultOpen = true;
          } else {
            this.$confirm("是否确认删除选择的数据项?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(function () {
                return delDylList(dylIds);
              })
              .then(() => {
                this.getList();
                this.msgSuccess("删除成功");
              })
              .catch(() => {});
          }
        });
      } else {
        this.$confirm("是否确认删除选择的数据项?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delDylList(dylIds);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(() => {});
      }
    },
    handleEdit(row) {
      this.isBatch = false;
      this.open = true;
      this.title = "修改";
      this.form = Object.assign({}, row);
      selectByOrders(this.form.dylFxdm, 0, 1).then((res) => {
        if (res.data && res.data.length > 0) {
          this.dyWldm = res.data;
          this.restaurants = this.dyWldm;
        } else {
          this.msgError("该父项bom无子级,请建立bom后再进行代用料维护!");
        }
      });
    },
    handleDyDefault(row) {
      if (row.dylDefult === "0") {
        getDylListById(row.dylId || this.ids).then((response) => {
          this.dylDefultList = response.data;
          if (this.dylDefultList.length > 0) {
            this.dylDefultOpen = true;
          } else {
            updateDylList(row).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.dylDefultOpen = false;
              this.getList();
            });
          }
        });
      } else {
        updateDylList(row).then((response) => {
          this.msgSuccess("修改成功");
          this.open = false;
          this.dylDefultOpen = false;
          this.getList();
        });
      }
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有代用料信息维护数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportDylList(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.percent {
  height: 40px;
  line-height: 40px;
  width: 10px;
  margin-left: 10px;
}
</style>
